package org.example.controller;

import org.example.pojo.*;
import org.example.service.CompanyService;
import org.example.service.JobService;
import org.example.service.ResumeService;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

import org.example.utils.JobAnalyzer;

@RestController
public class AnalysisController {
    @Autowired
    private JobService jobService;
    @Autowired
    private ResumeService resumeService;
    @Autowired
    private CompanyService companyService;
    // 实例化JobAnalyzer类
    JobAnalyzer analyzer = new JobAnalyzer();


    @PostMapping("/job/analysis1")
    public Result<List<Job>> analysisJob(String tags,String degree,String experience,String location){
        Map<String, String> WorkYear_low_up=analyzer.getWorkYear_low_up(experience);
        List<Job> list= jobService.analysisJobs(tags, degree, WorkYear_low_up.get("low_experience"),WorkYear_low_up.get("up_experience"), location);

        return Result.success(list);
    }
    @PostMapping("/job/JobRequirement")
    public Result<Map<String, Object>> JobRequirement(String tags, String degree, String experience, String location){
        Map<String, Object> analysisResults = new HashMap<>();
        Map<String, String> WorkYear_low_up=analyzer.getWorkYear_low_up(experience);
        List<Job> list= jobService.analysisJobs(tags, degree, WorkYear_low_up.get("low_experience"),WorkYear_low_up.get("up_experience"), location);

        Map<String, List<Job>> salarySegments = analyzer.SalaryGroup(list);
        // 对每个薪资段进行词频统计
        List[] results = new List[3];
        results[0] = analyzer.analyzeRequirements(salarySegments.get("lower25Percent"),20); // 后25%
        results[1] = analyzer.analyzeRequirements(salarySegments.get("middle50Percent"),20); // 中间50%
        results[2] = analyzer.analyzeRequirements(salarySegments.get("upper25Percent"),20); // 前25%
        List<Map.Entry<String, Double>> averages = new ArrayList<>();
        for (Map.Entry<String, List<Job>> entry : salarySegments.entrySet()) {
            String segmentName = entry.getKey();
            List<Job> jobsInSegment = entry.getValue();
            double sum = 0;
            for (Job job : jobsInSegment) {
                sum += job.getSalaryYear();
            }
            double averageSalaryYear = sum / jobsInSegment.size();
            // 将薪资段名和平均薪资作为一个Entry放入列表
            averages.add(new AbstractMap.SimpleEntry<>(segmentName, averageSalaryYear));
            analysisResults.put(segmentName, jobsInSegment.size());
        }
        // 添加averages到Map中
        analysisResults.put("averageSalaries", averages);
        analysisResults.put("lower25PercentRequirements", results[0]);
        analysisResults.put("middle50PercentRequirements", results[1]);
        analysisResults.put("upper25PercentRequirements", results[2]);


         return Result.success(analysisResults);
    }
    @PostMapping("/job/JobworkRole")
    public Result<Map<String, Object>> JobworkRole(String tags, String degree, String experience, String location){
        Map<String, Object> analysisResults = new HashMap<>();
        List<Job> list= jobService.analysisRole(tags,location);
        List<Job> developmentAndEngineeringList = new ArrayList<>();
        List<Job> architectureList = new ArrayList<>();
        List<Job> managementList = new ArrayList<>();
        for (Job job : list) {
            String workRole = job.getWorkRole().toLowerCase(); // 转换为小写，以便进行不区分大小写的匹配
            // 判断并添加到对应的列表中
            if (workRole.contains("开发") || workRole.contains("工程")) {
                developmentAndEngineeringList.add(job);
            }
            if (workRole.contains("架构")) {
                architectureList.add(job);
            }
            if (workRole.contains("团队") || workRole.contains("负责")
                    || workRole.contains("领导") || workRole.contains("管理")
                    || workRole.contains("主管") || workRole.contains("经理")) {
                managementList.add(job);
            }
        }

        analysisResults.put("devAndEngNum",developmentAndEngineeringList.size());
        analysisResults.put("archNum",architectureList.size());
        analysisResults.put("mgmtNum",managementList.size());

        double devAndEngAvg = analyzer.calculateAverageWorkYear(developmentAndEngineeringList);
        double archAvg = analyzer.calculateAverageWorkYear(architectureList);
        double mgmtAvg = analyzer.calculateAverageWorkYear(managementList);
//        System.out.println("开发与工程类工作的平均工作经验为: " + devAndEngAvg + " 年");
//        System.out.println("架构类工作的平均工作经验为: " + archAvg + " 年");
//        System.out.println("管理类工作的平均工作经验为: " + mgmtAvg + " 年");

        analysisResults.put("devAndEngAvg",devAndEngAvg);
        analysisResults.put("archAvg",archAvg);
        analysisResults.put("mgmtAvg",mgmtAvg);


        double devAndEngSalary = analyzer.calculateAverageSalaryYear(developmentAndEngineeringList);
        double archSalary = analyzer.calculateAverageSalaryYear(architectureList);
        double mgmtSalary = analyzer.calculateAverageSalaryYear(managementList);
//        System.out.println("开发与工程类工作的平均工作年薪为: " + devAndEngSalary + " K");
//        System.out.println("架构类工作的平均工作年薪为: " + archSalary + " K");
//        System.out.println("管理类工作的平均工作年薪为: " + mgmtSalary + " K");

        analysisResults.put("devAndEngSalary",devAndEngSalary);
        analysisResults.put("archSalary",archSalary);
        analysisResults.put("mgmtSalary",mgmtSalary);


        Map<String, Integer> devAndEngDegree = analyzer.countDegreeDistribution(developmentAndEngineeringList);
        Map<String, Integer> archDegree = analyzer.countDegreeDistribution(architectureList);
        Map<String, Integer> mgmtDegree = analyzer.countDegreeDistribution(managementList);

        analysisResults.put("devAndEngDegree",devAndEngDegree);
        analysisResults.put("archDegree",archDegree);
        analysisResults.put("mgmtDegree",mgmtDegree);


        return Result.success(analysisResults);
    }
    @PostMapping("/job/JobResume")
    public Result<Map<String, Object>> JobResume(String tags,String degree,Integer experience,String location,String skills){
        Map<String, Object> analysisResume = new HashMap<>();
        Map<String, String> WorkYear_low_up=analyzer.intGetWorkYear_low_up(experience);

        String low_experience=WorkYear_low_up.get("low_experience");
        String up_experience=WorkYear_low_up.get("up_experience");

        List<Job> list= jobService.analysisJobs(tags, degree, low_experience,up_experience, location);

        String[] splitArray = skills.split("[，,]");
        String[] lowerSplitArray = new String[splitArray.length];
        for (int i = 0; i < splitArray.length; i++) {
            lowerSplitArray[i] = splitArray[i].trim().toLowerCase();
        }
        List<Map.Entry<String, Integer>> results = analyzer.analyzeRequirements(list, 10);
        Map<String, Integer> noSkillMap = new HashMap<>();
//        Map<String, Integer> canSkillMap = new HashMap<>();
        Map<String, Integer> rankSkillMap = new HashMap<>();
        //        技术得分
        int job_num=0;
//        打印出排名前10的技术
        int rank_num=0;
        int skill_all=0;

        for (Map.Entry<String, Integer> entry : results) {
            Integer count = entry.getValue();
            String keyword = entry.getKey();
            rankSkillMap.put(keyword,count);
            boolean isMatched = false;
            for (String skill : lowerSplitArray) {
                if (entry.getKey().toLowerCase().contains(skill)) {
                    isMatched = true;
                    job_num=job_num+count;
                    break;
                }
            }
            if (!isMatched) {
                noSkillMap.put(keyword,count);
            }
            skill_all=skill_all+count;
        }





        analysisResume.put("rankSkillMap",rankSkillMap);
        analysisResume.put("noSkillMap",noSkillMap);
        analysisResume.put("jobSuitScore",job_num / (1.0 *skill_all));
        analysisResume.put("jobDifference",splitArray.length);
        int degreeScore=0;
        switch (degree) {
            case "大专" -> degreeScore = 40;
            case "本科" -> degreeScore = 70;
            case "硕士" -> degreeScore = 90;
            case "博士" -> degreeScore = 100;
        }
        analysisResume.put("degreeScore",degreeScore);
        double experienceScore=0;
        if (experience < 1) {
            experienceScore= 0; // 少于1年的经验得分为0
        } else if (experience >= 1 && experience < 3) {
            // 在1年到3年之间，每增加一年得分增加(60-50)/(3-1)
            experienceScore= 50 + (experience - 1) * ((60 - 50.0) / (3 - 1));
        } else if (experience >= 3 && experience < 5) {
            // 在3年到5年之间，每增加一年得分增加(87-60)/(5-3)
            experienceScore= 60 + (experience - 3) * ((87 - 60.0) / (5 - 3));
        } else if (experience >= 5 && experience < 10) {
            // 在5年到10年之间，每增加一年得分增加(100-87)/(10-5)
            experienceScore= 87 + (experience - 5) * ((100 - 87.0) / (10 - 5));
        } else {
            // 10年及以上经验得分为100
            experienceScore= 100;
        }
        analysisResume.put("experienceScore",experienceScore);

        double salary = analyzer.calculateAverageSalaryYear(list);
        double salaryScore = 0;
        if (salary <= 100) {
            salaryScore = 20;
        } else if (salary <= 300) { // 修改了这个条件，去掉了对500的判断，使其不与后面的条件冲突
            salaryScore = (salary - 100) * 0.3 + 20; // 确保在100到300之间线性增加
        } else if (salary <= 500) { // 修改条件范围以包含500，并调整计算公式以保证在300到500之间从80分增长到100分
            salaryScore = (salary - 300) * (100 - 80) / (500 - 300) + 80;
        } else { // 当salary > 500时
            salaryScore = 100;
        }
        analysisResume.put("salaryScore",salaryScore);

        return Result.success(analysisResume);
    }

    @PostMapping("/job/JobRecommend")
    public Result<JobDtoS> JobRecommend(){
        //从ThreadLocal中获取数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        Resume userResume = resumeService.selectByUserId(userId);
        String skills = userResume.getSkills();
        int experience=userResume.getExperiment();
        Map<String, String> WorkYear_low_up = analyzer.intGetWorkYear_low_up(experience);
        Map<Job, Integer> jobSuit = new HashMap<>();

        List<Job> list= jobService.analysisJobs(userResume.getIntention(), userResume.getDegree(), WorkYear_low_up.get("low_experience"),WorkYear_low_up.get("up_experience"), userResume.getLocation());
        //        自己会的技能
        String[] splitArray = skills.split("[，,]");

        for(Job test_list:list){
            String job_skills = test_list.getWorkRequirements();
//            岗位要求的技能
            String[] job_skillArray = job_skills.split("[，,]");
//            计算匹配的技术
            //  符合技术数量
            int job_skill_num=0;
            for(String skill : splitArray){
                for (String job_skill:job_skillArray){
//                    符合技术数量
                    skill=skill.toLowerCase();
                    job_skill=job_skill.toLowerCase();
                    // 使用contains()方法检查str1是否包含str2
                    boolean contains = job_skill.contains(skill);
                    if (contains){
                        job_skill_num=job_skill_num+1;
                        break;
                    }
                }
            }
            jobSuit.put(test_list,job_skill_num);
        }
        List<Map.Entry<Job, Integer>> sortedEntries = new ArrayList<>(jobSuit.entrySet());
        sortedEntries.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));
        sortedEntries = sortedEntries.subList(0, 50);


        List<Job> jobList = sortedEntries.stream()
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

        List<Integer> jobRecommend = sortedEntries.stream()
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());


        JobDtoS jobDtos = new JobDtoS();
        List<Job> jobDtoList = new ArrayList<>();
        List<Company> companyList = new ArrayList<>();
        for (Job job :jobList) {
            Company company = companyService.selectByCompanyId(job.getCompanyId());
            jobDtoList.add(job);
            companyList.add(company);
        }
        jobDtos.setJob(jobDtoList);
        jobDtos.setCompany(companyList);
        jobDtos.setJobRecommend(jobRecommend);
        return Result.success(jobDtos);
    }

    @PostMapping("/job/recruitAnalysis")
    public Result<Map<String, Object>> recruitAnalysis(String tags,String degree,String experience,String location,String role,Integer jobSalaryYear){
        Map<String, String> WorkYear_low_up=analyzer.getWorkYear_low_up(experience);
        Map<String, Object> analysisRecruit = new HashMap<>();
        List<Job> list= jobService.analysisJobs(tags, degree, WorkYear_low_up.get("low_experience"),WorkYear_low_up.get("up_experience"), location);
        List<Job> developmentAndEngineeringList = new ArrayList<>();
        List<Job> architectureList = new ArrayList<>();
        List<Job> managementList = new ArrayList<>();
        List<Job> roleList = new ArrayList<>();
        for (Job job : list) {
            String workRole = job.getWorkRole().toLowerCase(); // 转换为小写，以便进行不区分大小写的匹配
            // 判断并添加到对应的列表中
            if (workRole.contains("开发") || workRole.contains("工程")) {
                developmentAndEngineeringList.add(job);
            }
            if (workRole.contains("架构")) {
                architectureList.add(job);
            }
            if (workRole.contains("团队") || workRole.contains("负责")
                    || workRole.contains("领导") || workRole.contains("管理")
                    || workRole.contains("主管") || workRole.contains("经理")) {
                managementList.add(job);
            }
        }
        switch (role) {
            case "0" -> {
                roleList = developmentAndEngineeringList;
//                analysisRecruit.put("roleList", developmentAndEngineeringList);
            }
            case "1" -> {
                roleList = architectureList;
//                analysisRecruit.put("roleList", architectureList);
            }
            case "2" -> {
                roleList = managementList;
//                analysisRecruit.put("roleList", managementList);
            }
        }
        List<Job> sortedList = roleList.stream()
                .sorted(Comparator.comparingInt(Job::getSalaryYear).reversed())
                .toList();
        int rank = 1; // 初始化排名为1，因为我们总是至少与自己比较
        for (Job job : sortedList) {
            Integer salaryYear = job.getSalaryYear();
            if (salaryYear>jobSalaryYear){
                rank++;
            }
            else {
                break;
            }
        }
        analysisRecruit.put("roleList", sortedList);
        analysisRecruit.put("rank", rank);
        analysisRecruit.put("roleListNum", sortedList.size());

        return Result.success(analysisRecruit);
    }
    @PostMapping("/job/resumeRecommend")
    public Result<List<Resume>> recruitAnalysis(Integer jobId){
        Job job=jobService.findJobById(jobId);
        String workRequirements=job.getWorkRequirements();
        String tags=job.getTags();
        String[] splitArray = workRequirements.split("[，,]");
        // 将splitArray转换为小写并存储到一个新的数组中，以便后续比较
        String[] lowerSplitArray = new String[splitArray.length];
        for (int i = 0; i < splitArray.length; i++) {
            lowerSplitArray[i] = splitArray[i].trim().toLowerCase();
        }
        List<Resume> Resume_list=resumeService.findResumeByTags(tags);
        Map<Resume, Integer> Resume_rank = new HashMap<>();
        for (Resume resume:Resume_list){
//            符合技能的数量
            int resume_skill_num=0;
//            简历技能
            String resume_skills=resume.getSkills();
            String[] resumesplitArray = resume_skills.split("[，,]");
            // 将splitArray转换为小写并存储到一个新的数组中，以便后续比较
            String[] resumelowerSplitArray = new String[resumesplitArray.length];
            for (int i = 0; i < resumesplitArray.length; i++) {
                resumelowerSplitArray[i] = resumesplitArray[i].trim().toLowerCase();
            }
            for (String resume_skill:resumelowerSplitArray){
                for (String job_skill:lowerSplitArray){
                    boolean contains = job_skill.contains(resume_skill);
                    if (contains){
                        resume_skill_num=resume_skill_num+1;
                        break;
                    }
                }

            }
            Resume_rank.put(resume,resume_skill_num);
        }

        List<Map.Entry<Resume, Integer>> top50Entries = Resume_rank.entrySet().stream()
                .sorted(Map.Entry.<Resume, Integer>comparingByValue().reversed())
                .limit(50)
                .toList();

        List<Resume> top50Resumes = top50Entries.stream()
                .map(Map.Entry::getKey)
                .toList();

        return Result.success(top50Resumes);
    }
    }
